package com.canyou.expression;

import com.canyou.system.service.UserService;
import com.canyou.utils.Oauth2Utils;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;

import java.util.List;

/**
 * 方法权限表达式解析
 *
 * @author canyou
 */
public class CysMethodSecurityExpressionRoot extends SecurityExpressionRoot
        implements MethodSecurityExpressionOperations {

    private UserService userService;

    private Object filterObject;
    private Object returnObject;
    private Object target;

    public CysMethodSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public boolean hasPerm(String... permissions) {
        String userName = Oauth2Utils.getUserName();
        List<String> permissionList = null;
        permissionList = userService.getMenuListByUserName(userName);
        for (String permission : permissions) {
            if (permissionList.contains(permission)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object getFilterObject() {
        return this.filterObject;
    }

    @Override
    public void setFilterObject(Object filterObject) {
        this.filterObject = filterObject;
    }

    @Override
    public Object getReturnObject() {
        return this.returnObject;
    }

    @Override
    public void setReturnObject(Object returnObject) {
        this.returnObject = returnObject;
    }

    @Override
    public Object getThis() {
        return this.target;
    }

    void setThis(Object target) {
        this.target = target;
    }
}